/**
 * we feed列表
 */
define(['../../common/service','../../common/copybox', '../../model/currency'],
    function( http,  CB, currency){
        var catalogData;
        /**
         * 根据属性去重
         * @param list
         * @param p 属性名称
         * @returns {Array}
         */
        _.uniqBy=function(list,p){
            var ids=new Set();
            var r=[];
           $.each(list, function(i, _d){
               if (!ids.has(_d[p])) {
                   ids.add(_d[p]);
                   r.push(_d);
               }
           })
            return r;
        };
        var feedList = {
            init: function (query) {
                var _this = this;
                //列表管理
                $('table[list-manager="feedList"]').listManager('init',{
                    setTopVal:135 //调整吸顶的高度,需要减去这个高度
                    ,scrollDOM:$('.fmp-article')//监听滚动条
                    ,supportAjaxPage: true
                    ,pageCallback:function(query){
                        $.extend(_this._query, query);
                        _this.getList();
                    }
                }, function(query){
                    _this.bindDetailPageEvent();
                    _this.bindFetchNow();
                    _this.bindRetry();
                    _this.bindCatalogClick();
                    _this.bindAvailable();
                    _this._query = query;
                    _this.getList();
                });

                if (window.sessionStorage.roleId.indexOf(1) > -1) {
                    $('#add-feed-btn').removeClass('hidden');
                    _this.bindAddFeedEvent();
                }
                _this.add_btn_event($('.feed-urls .add-btn'));
                _this.remove_btn_event($('.feed-urls  .remove-btn'));
                _this.bindCatalogEvent();

            }

            , bindCatalogEvent: function () {
                var self=this;
                ////表格事件
                //var catalogList=$(".ndp-table-wrapper[name='solid-sort-table']").table({
                //    head:{order:"id",name:"名称",bussinessId:"bussinessId"},
                //    data:[ {id:"<input catalog='1' type='checkbox'>",name:"hello_23", bussinessId:"2"},
                //        {id:"<input catalog='2' type='checkbox'>",name:"asfasdf", bussinessId:"2"}],
                //    sort:[1]
                //}).on("ROW_CLICK",function(e){//行被点击
                //    console.log(e.originalEvent.data);// {row：第几行 int}//第几行
                //});
                //搜索框事件
                $(".ndp-search-wrapper[name=plain]").search({
                    placeholder:"Search",
                    name:"q"//为了方便serialize 建议设置name 属性
                }).on("INPUT_CHANGE",function(e){//input输入内容发生改变 触发
                    console.log(e.originalEvent.data);//{text:输入内容}
                }).on("do_search",function(e){
                    //add by Evan 2016-07-27 已经绑定过的再怎么过滤查询 也得出现在结果集中
                    var checked=$("#modal-bindCatalog table tbody").find("input:checked");
                    var catalogs=[];
                    $.each(checked,function(i,v){
                        catalogs.push($(v).attr("catalog"));
                    });

                    var key = e.originalEvent.data;
                    var result= _.filter(catalogData,function(i){
                        return i.id.indexOf(key.text)>-1
                            ||i.name.indexOf(key.text)>-1
                            ||i.businessId.toString().indexOf(key.text)>-1
                            || $.inArray($(i.id).attr("catalog"), catalogs) > -1;
                    });

                    var feedId = $("#modal-bindCatalog").attr("feed");

                    self.queryBindedCatalog(feedId,function(ids){
                        self.renderCatalogTable(result,ids);
                    });
                    //catalogList.update(result);
                    //self.renderCatalogTable(result);
                });
                //提交事件
                $("#modal-bindCatalog button[confirm]").off("click").on("click",function(e){
                    var  feedId=$("#modal-bindCatalog").attr("feed");
                    var checked=$("#modal-bindCatalog table tbody").find("input:checked");
                    var catalogs=[];
                    $.each(checked,function(i,v){
                        var catalog ={id:$(v).attr("catalog"),name:$(v).attr("name")};
                        catalogs.push(catalog);
                    });
                    var param={
                        wefeedId:feedId,
                        catalogs:catalogs
                    };
                    http.work("/catalog/bind",param,"post").then(function(d){
                        if (!d.succeed) {
                            Kit.alert2(d.errorMsg)
                        } else {
                            self.getList();
                        }
                    });
                    $("#modal-bindCatalog").modal("hide");
                })
            },
            getCatalogDatas:function(feedId,callback){
                http.work("/catalog/all?feedId="+feedId,"get").then(function(d){
                    if (d.succeed) {
                        var result=  d.data.map(function(v,i){
                            v.id="<input catalog="+v.id+" name='"+v.name+"' type='checkbox'>"+ v.id+"</input>";
                            return v;
                        });
                        if (callback) callback(result);
                    }else{
                        Kit.alert3(I18N.getText('feedList','getCatalogFail'));
                    }
                });
            },
            queryBindedCatalog:function(feedId,callback){
                http.work("/catalog/byFeed?feedId="+feedId,"get").then(function(d){
                    if (d.succeed) {
                        var catalogIds=  d.data.map(function(v,i){
                            return v.fbProductCatalogId;
                        });
                        if(callback) callback(catalogIds);
                    }else{
                        Kit.alert3(I18N.getText('feedList','getBindCatalogFail'));
                    }
                });
            }

            /*
             @绑定添加产品事件
             */
            ,bindAddFeedEvent : function(){
                var _this = this;
                var _addProductModal= $(".dialog-add-feed");
                _addProductModal.modal({
                    backdrop: 'static',
                    keyboard: false,
                    show:false
                });
                //modal初始化
                _addProductModal.on('show.bs.modal', function(){
                    _addProductModal.find("input").val("");
                    _addProductModal.find("textarea").val("");

                    //feed名称重名校验
                    _addProductModal.find('.feedName').change(function(){
                        var _thisName = $(this);
                        var nameV = $.trim(_thisName.val());
                        if(Kit.isBlank(nameV))
                            return;
                        var paramFeedName = {
                            feedName : nameV
                        }
                        http.work('/feed/validate',paramFeedName,'POST').then(function(res){
                            if (res.succeed){
                                if(res.data == 2) {
                                    Kit.alert2(I18N.getText('feedList','feedNameRepeat'));
                                    _thisName.addClass("form-input-warning");
                                    _thisName.val("").focus();
                                } else if(res.data == 1) {
                                    _thisName.removeClass("form-input-warning");
                                }
                            } else {
                                Kit.alert2(res.errorMsg);
                                return false;
                            }
                        });
                    });

                    //选择产品
                    http.work('/productmanage/get', null,'GET').then(function(res){
                        if(res.succeed){
                            var prodArr = [{id: -1,text: I18N.getText('feedList', 'pleaseSelectProduct')}];
                            if(res.data){
                                for(var b = 0; b<res.data.length;b++) {
                                    prodArr.push({id: res.data[b].prodId,text: res.data[b].prodName});
                                }
                            }
                            if(res.data.length == 0)
                                Kit.alert2(I18N.getText('feedList', 'pleaseCreateProductFirst'));

                            _addProductModal.find('select[name="product"]').empty().select2({
                                minimumResultsForSearch: Infinity,
                                data : prodArr
                            });
                        }
                    });

                    //货币
                    var cur = currency[I18N.language];
                    var curHtml = '<option value="-1">' + I18N.getText('feedList', 'setCurrency') + '</option>';
                    for(var c = 0; c< cur.length; c++){
                        curHtml += '<option value="'+cur[c].unit+'">&nbsp;' +cur[c].unit+ '--' + cur[c].name + '</option>';
                    }
                    var curSelect = _addProductModal.find('select[name="currency"]');
                    curSelect.empty();
                    curSelect.html(curHtml);
                    curSelect.select2();

                    $("#selectBm").hide();
                    $(".dialog-add-feed input[type=radio]").click(function (e) {
                            if ($(this).attr("id") == "newCatalog") {
                                $("#selectBm").show();
                            } else {
                                $("#selectBm").hide();
                            }
                        }
                    );
                    //bm
                    http.work('/entrustaccounts/businessManagersAdmin', null,'GET').then(function(res){
                        if(res.flag == 'success'){
                            var bmArr = [{id: -1,text: I18N.getText('feedList', 'setBm')}];
                            if(res.data.businessmanagers){
                                for(var b = 0; b<res.data.businessmanagers.length;b++) {
                                    bmArr.push({id: res.data.businessmanagers[b].fbBusinessesId,text: res.data.businessmanagers[b].name});
                                }
                            }
                            _addProductModal.find('select[name="bm"]').empty().select2({
                                minimumResultsForSearch: Infinity,
                                data : bmArr
                            });
                        }
                    });

                    var dayOfWeekDiv = $("div.ndp-drop-wrapper[name=dayOfWeek-drop]");
                    var dayOfWeekSymbol = $("span[name=dayOfWeek-symbol]");
                    //调度
                    $("div.ndp-drop-wrapper[name=interval-drop]").empty().drop({
                        data:[{
                            value: 'DAILY',
                            text: I18N.getText('feedList', 'daily')
                        }],
                        name:"interval"
                    }).off("ITEM_CLICK").on("ITEM_CLICK",function(e){
                        var val = e.originalEvent.data.val;
                        if('DAILY' == val) {
                            dayOfWeekDiv.addClass('hidden');
                            dayOfWeekSymbol.addClass('hidden');
                        } else if ('WEEKLY' == val) {
                            dayOfWeekDiv.removeClass('hidden');
                            dayOfWeekSymbol.removeClass('hidden');
                            dayOfWeekDiv.empty().drop({
                                data:[{
                                    value: 'MONDAY',
                                    text: I18N.getText('feedList', 'monday')
                                },{
                                    value: 'TUESDAY',
                                    text: I18N.getText('feedList', 'tuesday')
                                },{
                                    value: 'WEDNESDAY',
                                    text: I18N.getText('feedList', 'wednesday')
                                },{
                                    value: 'THURSDAY',
                                    text: I18N.getText('feedList', 'thursday')
                                },{
                                    value: 'FRIDAY',
                                    text: I18N.getText('feedList', 'friday')
                                },{
                                    value: 'SATURDAY',
                                    text: I18N.getText('feedList', 'saturday')
                                },{
                                    value: 'SUNDAY',
                                    text: I18N.getText('feedList', 'sunday')
                                }],
                                name:"dayOfWeek"
                            }).off("ITEM_CLICK").on("ITEM_CLICK",function(e){
                                console.log(e.originalEvent.data);
                            }).val({
                                value: 'MONDAY',
                                text: I18N.getText('feedList', 'monday')
                            });
                        }
                    }).val({
                        value: 'DAILY',
                        text: I18N.getText('feedList', 'daily')
                    });

                    $("div.ndp-drop-wrapper[name=hour-drop]").empty().drop({
                        data: _this.getHour(),
                        name:"hour"
                    }).off("ITEM_CLICK").on("ITEM_CLICK",function(e){
                        console.log(e.originalEvent.data);
                    }).val({
                        value: '0',
                        text: '00:00'
                    });
                });

                //标题输入框禁止回车事件
                _addProductModal.off("keydown", "textarea,input").on("keydown", "textarea,input", function(e){
                    //禁止回车
                    if (e.keyCode == 13) {
                        return false;
                    }
                });

                //保存并抓取事件
                _addProductModal.find('button[saveAndFetch]').off("click").on("click", function(e){
                    var param = _this.getSaveFeedParams();
                    //校验
                    if (!_this.validateSaveFeedParams()) {
                        return;
                    }
                    //提交数据
                    var loadingAray = $('.dialog-add-feed .modal-dialog');
                    Kit.loading.show(loadingAray);
                    http.work('/feed/save',param,'POST').then(function(res){
                        Kit.loading.hide(loadingAray);
                        if (res.succeed){
                            _addProductModal.modal("hide");
                            //重新刷新列表
                            _this.getList();
                        } else {
                            Kit.alert2(res.errorMsg);
                            return false;
                        }
                    });
                });

                //保存feed事件
                _addProductModal.find('button[save]').off("click").on("click", function(e){
                    var param = _this.getSaveFeedParams();
                    //校验
                    if (!_this.validateSaveFeedParams()) {
                        return;
                    }
                    // 发起请求
                    //提交数据
                    var loadingAray = $('.dialog-add-feed .modal-dialog');
                    Kit.loading.show(loadingAray);
                    http.work('/feed/save',param,'POST').then(function(res){
                        Kit.loading.hide(loadingAray);
                        if (res.succeed){
                            _addProductModal.modal("hide");
                            //重新刷新列表
                            _this.getList();
                        } else {
                            Kit.alert2(res.errorMsg);
                            return false;
                        }
                    });
                });
                $("#add-feed-btn").off("click").on("click", function(){
                    $("#oldCatalog").prop("checked", "checked");
                    _addProductModal.modal("show");
                });
            }
            ,add_btn_event: function ($Dom) {
                var self = this;
                var node = '<div class="feed-urls-wrapper"><input type="text" class="urlInput" placeholder="'+I18N.getText('feedList', 'pleaseInputFeedUrl')+'"/>'
                    + '<button type="button" class="close" data-dismiss="alert" aria-label="Close" ><span aria-hidden="true"'
                    + ' style="font-size: 27px;">&times;</span></button></div>';
                $Dom.unbind("click").bind("click", function (e) {
                    var $Dom = $(this).parent().append(node);
                    var _removeD = $Dom.find(".close");
                    $(this).parent().find(".close").removeClass("hidden");
                    self.remove_btn_event(_removeD);
                    return false;
                });
            }
            ,remove_btn_event: function ($Dom) {
                $Dom.unbind("click").on("click", function (e) {
                    var _parentWrapper = $(this).parent();
                    var _brothers = _parentWrapper.siblings("div").length;
                    if (1 == _brothers) {
                        //最后一个不能删除
                        _parentWrapper.parent().find("button.close").addClass("hidden");
                    }
                    _parentWrapper.remove();
                    return false;
                });
            }
            /*
             @绑定搜索事件
             */
            ,getSaveFeedParams: function(){
                var params = {};
                var _addProductModal= $(".dialog-add-feed");
                params.feedName = $.trim(_addProductModal.find('input.feedName').val());
                params.productId = _addProductModal.find('select[name="product"]').val();
                params.currency = _addProductModal.find('select[name="currency"]').val();
                params.bmId = _addProductModal.find('select[name="bm"]').val();
                params.promotedWebsite = $.trim(_addProductModal.find('input[name="promotedWebsite"]').val());
                params.interval= _addProductModal.find('input[name="interval"]').data('val');
                params.dayOfWeek= _addProductModal.find('input[name="dayOfWeek"]').data('val');
                params.hour= _addProductModal.find('input[name="hour"]').data('val');
                params.utmSource = $.trim(_addProductModal.find('input.utmSource').val());
                params.utmMedium = $.trim(_addProductModal.find('input.utmMedium').val());
                params.utmTerm = $.trim(_addProductModal.find('input.utmTerm').val());
                params.utmContent = $.trim(_addProductModal.find('input.utmContent').val());
                params.utmCampaign = $.trim(_addProductModal.find('input.utmCampaign').val());
                params.utmCustom = $.trim(_addProductModal.find('input.utmCustom').val());
                params.operateStatus=_addProductModal.find('input[name=createCatalog]:checked').attr("id")=="oldCatalog"?"unbind_catalog":"";

                var urlArr = new Array();
                $('input.urlInput').each(function(k){
                    if(!Kit.isBlank($(this).val())){
                        urlArr.push($(this).val());
                    }
                })
                var urlObj = {
                    urls : urlArr
                };
                params.originUrls = JSON.stringify(urlObj);
                return params;
            }
            /*
             @ 添加feed保存前 入参校验
             */
            ,validateSaveFeedParams: function(){
                var _this = this;
                var params = _this.getSaveFeedParams();
                //feed名称不能为空
                if (Kit.isBlank(params.feedName)){
                    Kit.alert2(I18N.getText('feedList','enterFeedName'));
                    return false;
                }
                //产品必选
                if (Kit.isBlank(params.productId) || params.productId == '-1'){
                    Kit.alert2(I18N.getText('feedList','pleaseSelectProduct'));
                    return false;
                }

                //货币必选
                if (Kit.isBlank(params.currency) || params.currency == '-1'){
                    Kit.alert2(I18N.getText('feedList','setCurrency'));
                    return false;
                }
                //只有新建的时候才验证bm
                if ($(".dialog-add-feed").find('input[name=createCatalog]:checked').attr("id") == "newCatalog") {
                    //bm
                    if (Kit.isBlank(params.bmId) || params.bmId == '-1'){
                        Kit.alert2(I18N.getText('feedList','pleaseSelectBm'));
                        return false;
                    }
                }

                //推广网址
                if (Kit.isBlank(params.promotedWebsite)){
                    Kit.alert2(I18N.getText('feedList','enterPromotedWebsite'));
                    return false;
                }
                //todo 推广网址格式校验

                //feedUrl不能为空
                var urlInputNull = false;
                $('input.urlInput').each(function(k){
                    if(Kit.isBlank($(this).val())){
                        Kit.alert2(I18N.getText('feedList','enterFeedUrl', k+1));
                        $(this).focus();
                        urlInputNull = true;
                    }
                })
                if(urlInputNull)
                    return false;
                return true;
            }
            /*
             @获取列表数据
             */
            ,getList:function(){
                var _this = this;
                var loadingArea = $('.feeds-table');
                Kit.loading.show(loadingArea);
                http.work('/feed/getList',_this._query,'POST').then(function(res){
                    if (res.succeed){
                        //操作DOM节点更换数据
                        var data = res.data;
                        var _table = $('table[list-manager="feedList"]'),
                            _tbody = $('#feeds-grid', _table),
                            tmpHtml = '',
                            _serial = 0,		//序号
                            _list = data.feeds,
                            _paginator = data.paginator;

                        if(_list) {
                            for(var i=0; i< _list.length; i++){
                                _serial = (_paginator.cPage-1) * _paginator.pSize +i + 1;
                                tmpHtml += _this.generateHTML(_list[i],_serial);
                            }
                        }
                        _tbody.html(tmpHtml);
                        _table.listManager([{'resetTd':false, 'resetPageData': _paginator}]);

                        //实时更新feed发布状态
                        _this.updataState();
                    } else {
                        Kit.alert2(res.errorMsg);
                    }
                    Kit.loading.hide(loadingArea);
                });
            }
            /*
             @生成HTML
             */
            ,generateHTML: function(obj,_serial){
                var tmpHtml 	= '', //单条数据
                    statusClass = ''; //发布状态使用className

                var timezoneValue = window.sessionStorage.timezoneValue;
                var updateBtnShow = (obj.operateStatus == 'feedwe_create_ok' || obj.operateStatus == 'feedwe_update_ok' || obj.operateStatus == 'no_product');
                var retryBtnShow = (obj.operateStatus == 'send_catalog_fail' || obj.operateStatus == 'bind_catalog_pixel_fail' || obj.operateStatus == 'send_fbfeed_fail'
                || obj.operateStatus == 'url_merge_fail' || obj.operateStatus == 'xml_check_fail');
                var isBindCatalog = !(obj.operateStatus == 'unbind_catalog');
                var available = ((typeof(obj.available) === "undefined") ? 'pass':obj.available);
                var availableContent = updateBtnShow ? ('<img src="./imgs/feed-'+available+'.png" class="feedListImg">') : obj.operateStatus;

                var btnFetchNow;
                if (updateBtnShow) {
                    btnFetchNow = '<button type="button" class="btn btn-link fetchnow-action">' +
                        '<i  title="'+ I18N.getText('feedList', 'updateNow') +'" class="fa fa-retweet" style=" font-size: 18px;"></i>' +
                        '</button>';
                } else {
                    btnFetchNow = "";
                    statusClass ="p-ongoing"
                }
                var btnBindCatalog='<button type="button" title="' + I18N.getText('feedList', 'bindProductCatalog') + '" class="btn btn-link bind-action"><i class="fa fa-exchange" style="font-size: 18px;"></i></button>';
                var btnRetry='<span class="retry">' + I18N.getText('feedList', 'retry') + '</span>';

                var action;
                if (!isBindCatalog) {
                    action=btnBindCatalog;
                }else{
                    if(obj.bmId<1){
                        if(retryBtnShow) {
                            action=btnRetry+btnBindCatalog;
                        }else {
                            action=btnFetchNow +btnBindCatalog;
                        }
                    }else{
                        if(retryBtnShow) {
                            action=btnRetry;
                        }else {
                            action=btnFetchNow;
                        }
                    }
                }

                var bbb = {
                    avail : obj.catalogs
                }


                tmpHtml += '<tr wefeedid="'+obj.id+'" class="'+statusClass+'" productcnt ="'+obj.productCnt+'" avail='+ JSON.stringify(bbb) +'>'
                    +'<td class="serial number-show">' + (_serial || '') +'</td>'
                    +'<td><button type="button" class="btn btn-link edit-action">' +obj.feedName +'</button></td>'
                    +'<td title="' + obj.productName + '">' +obj.productName +'</td>'
                    +'<td title="' +  obj.operateStatus + '">' +((typeof(obj.productCnt) === "undefined") ? '':obj.productCnt) +'</td>'
                    +'<td>' +obj.currency +'</td>'
                    +'<td>' + ((typeof(obj.used) === "undefined") ? '0':obj.used) +'/'+  ((typeof(obj.canUse) === "undefined") ? '0':obj.canUse) +'</td>'
                    +'<td>'+availableContent+'</td>'
                    +'<td>' + (window.sessionStorage.roleId.indexOf(1) > -1 ? action : ' --- ') + '</td>'
                    +'<td>' + moment(obj.updateTime == 0 ? obj.createTime : obj.updateTime).utcOffset(timezoneValue).format('YYYY-MM-DD HH:mm') +'</td>'
                    +'</tr>'

                return tmpHtml;
            }
            /*
             @实时更新广告发布状态
             */
            ,updataState: function(){
                var _this = this;
                var _tbody = $('#feeds-grid'),
                    ongoingList = _tbody.find('.p-ongoing');
                if(ongoingList.length == 0){
                    window.clearTimeout(_this.stoupdataState);
                    return false;
                }
                console.log('当前共有['+ongoingList.length+']条数据需要实时更新');

                var weFeedIds = [];
                for(var i=0; i<ongoingList.length; i++){
                    weFeedIds.push(ongoingList.eq(i).attr('wefeedid'));
                }
                http.work('/feed/searchByIds',weFeedIds,'POST').then(function(res){
                    var tmpHtml = '',
                        _list = res.data,
                        _tbody = $('#feeds-grid'),
                        _tr,
                        _newTr,
                        _serial = 0;		//序号
                    if(!_list || _list.length == 0){
                        console.log('返回数据为空，已跳出对列表区域DOM节点的渲染');
                        return false;
                    }
                    for(var i=0; i< _list.length; i++){
                        _tr = _tbody.find('tr[wefeedid="'+_list[i].id+'"]');
                        if(!_tr || _tr.length != 0){ //??
                            _serial = _tr.find('.serial').text();
                            tmpHtml = _this.generateHTML(_list[i], _serial);
                            _newTr = $(tmpHtml).hide();
                            _tbody.append(_newTr);
                            _newTr.listManager('resetTd', true);
                            _tr.replaceWith(_newTr);
                            _newTr.show();
                            _tr.remove();
                        }
                    }
                });
                //定时刷新数据
                _this.stoupdataState = window.setTimeout(function(){
                    _this.updataState();
                },5000);
            }
            /*
             @绑定更改状态事件
             */
            ,bindEditStatusEvent: function(){
                var _this = this;
                var _tbody = $('#feeds-grid');
                _tbody.off('click', '.switcher');
                _tbody.on('click', '.switcher', function(e){
                    var _toggle 	= $(this),
                        _action	= $('input[name="checkbox-toggle"]', _toggle),
                        _tr 		= _action.parents('tr').eq(0),
                        _id 		= _tr.attr('data-id'),
                        _editAction;
                    if(_action.parent().hasClass('no-click')){
                        _editAction = _tr.find('.edit-action');
                        _editAction.animate({
                            opacity: 0.3
                        },300);
                        _editAction.animate({
                            opacity: 1
                        },300);
                        _editAction.animate({
                            opacity: 0.3
                        },300);
                        _editAction.animate({
                            opacity: 1
                        },300);
                        Kit.alert2(I18N.getText('adPublishCondition','setFirst'))
                        return false;
                    }
                    if(_toggle.hasClass('edit-ing')){
                        return false;
                    }

                    var par = {
                        id: _id,
                        status: _action.parent().hasClass("active") ? 0 : 1
                    }
                    var _loadIcon = $('<span class="fa fa-refresh refresh-rotation"></span>');
                    _toggle.append(_loadIcon);
                    _toggle.addClass('edit-ing');

                    http.work('/adpublishcondition/updateStatus', par,'POST').then(function(res){
                        if(res.flag == 'success'){
                            //_action.get(0).checked = res.data.status == 1 ? true : false;
                            if(res.data.status == 1)
                                _action.parent().addClass("active");
                            else
                                _action.parent().removeClass("active");
                        }
                        else{
                            Kit.alert2(res.msg || I18N.getText('adPublishCondition','editFailed'));
                        }
                        _toggle.removeClass('edit-ing');
                        _loadIcon.fadeOut(300,function(){
                            $(this).remove();
                        });
                    });
                    return false;
                });
            }
            /*
             @详情页事件
             */
            ,bindDetailPageEvent: function(){
                //绑定进入详情页事件
                $('#feeds-grid').off('click', '.edit-action');
                $('#feeds-grid').on('click', '.edit-action', function(){
                    var _action = $(this);
                    var _tr = _action.closest('tr');
                    var _weFeedId = _tr.attr('wefeedid');
                    var productcnt = _tr.attr('productcnt');
                    console.log(_weFeedId);
                    window.localStorage.setItem('weFeedId', _weFeedId);
                    window.localStorage.setItem('weFeedProductCnt', productcnt);
                    window.top.open('#!feedOverview')
                });
            },
            bindCatalogClick:function(){
                var self=this;
                $('#feeds-grid')
                    .off('click', '.bind-action')
                    .on('click', '.bind-action', function(){
                        var feedId=$(this).closest("tr").attr("wefeedid");
                        $("#modal-bindCatalog").attr("feed", feedId);
                        Kit.loading.show($("#modal-bindCatalog .modal-body"));
                        //请求全部catalog
                        self.getCatalogDatas(feedId,function(datas){
                            // 根据id 去重，因为多个BusinessId 可能同时有同一个catalog。
                            datas=_.uniqBy(datas,"id");
                            catalogData = datas;
                            //请求已绑定catalog
                            self.queryBindedCatalog(feedId,function(ids){
                                var bounds;
                                if (_.isEmpty(ids)) {
                                    // 第一次绑定显示全部
                                    bounds=datas;
                                }else{
                                    //否则只显示已绑定的catalog
                                    bounds=datas.filter(function(i){
                                        var catalogId=Number($(i.id).attr("catalog"));
                                        return ids.includes(catalogId);
                                    });
                                }
                                self.renderCatalogTable(bounds,ids);
                                Kit.loading.hide($("#modal-bindCatalog .modal-body"));
                            });
                        });
                        //初始化清空
                        $("#modal-bindCatalog table tbody").html("");
                        $("#modal-bindCatalog").modal();
                });
            },
            /*渲染产品目录表格
            *datas : 全部数据
            *selected ： 已选择数据
            */
            renderCatalogTable:function(datas,selected){
                console.log(selected)
                var temp='<% _.forEach(datas,function(d){ %>' +
                    '<tr>' +
                    '<td><%=d.id%></td>' +
                    '<td><%=d.name%></td>' +
                    '<td><%=d.businessId%></td>' +
                    '</tr>' +
                    '<%});%>';
                var result=_.template(temp)({"datas":datas});
                $("#modal-bindCatalog table tbody").html(result);

                //回显
                var inputs = $("#modal-bindCatalog table tbody input").toArray();

                if (!_.isEmpty(selected)) {
                    var inputSelected=inputs.filter(function (i) {
                        var catalogId =Number($(i).attr("catalog"));
                        return selected.includes(catalogId);
                    });
                    inputSelected.forEach(function(i){
                        $(i).attr("checked", true);
                    })
                }
            }
            /*
             @绑定feed 创建失败重试
             */
            ,bindRetry : function(){
                var _this = this;
                $('#feeds-grid').off('click', '.retry');
                $('#feeds-grid').on('click', '.retry', function(){
                    var _retry = $(this);
                    var _tr = _retry.closest('tr');
                    var params = {
                        id :_tr.attr('wefeedid'),
                        operateStatus:_tr.attr('status')
                    };
                    http.work('/feed/retry',params,'POST').then(function(res){
                        console.log(res);
                        if (res.succeed){
                            _this.getList();
                        }
                    });
                });
            }

            /*
             @看wefeed详细错误
             */
            ,bindAvailable : function(){
                var _this = this;
                $('#feeds-grid').off('mouseenter', '.feedListImg').on('mouseenter', '.feedListImg', function(ev){
                    var avail = JSON.parse($(this).closest('tr').attr('avail'));
                    if(avail && avail.avail) {
                        var box = $('#box1');
                        box.empty();
                        var mousePos = _this.mouseCoords(ev);
                        box.css('left', (mousePos[0]-150)+'px');
                        box.css('top', (mousePos[1]-100)+'px');
                        _.each(avail.avail, function(el) {
                            box.append('<p>'+ I18N.getText('feedList', 'productCatalog') +'：'+ el.fbProductCatalogId+'&nbsp;&nbsp;('+ el.available +')</p>');
                        });
                        box.removeClass('hidden');
                    }
                });
                $('#feeds-grid').off('mouseleave', '.feedListImg').on('mouseleave', '.feedListImg', function(ev){
                    $('#box1').addClass('hidden');
                });
            }
            , mouseCoords: function (evt) {
                var xPos,yPos;
                evt=evt || window.event;
                if(evt.pageX){
                    xPos=evt.pageX;
                    yPos=evt.pageY;
                } else {
                    xPos=evt.clientX+document.body.scrollLeft -document.body.clientLeft;
                    yPos=evt.clientY+document.body.scrollTop-document.body.clientTop;
                }
                return [xPos, yPos];
            }

        /*
         @绑定feed 立即抓取
         */
            ,bindFetchNow: function(){
                var _this = this;
                //渲染弹出框
                var fetchModal= $('#fetch-modal'),
                    confirmAction = $('button[confirm]', fetchModal);
                fetchModal.modal({
                    backdrop: 'static',
                    keyboard: false,
                    show: false
                });

                var _weFeedId,_tr;
                //绑定重试事件
                $('#feeds-grid').off('click', '.fetchnow-action');
                $('#feeds-grid').on('click', '.fetchnow-action', function(){
                    var _action = $(this);
                    if(_action.hasClass('disabled'))
                        return;
                    _tr = _action.closest('tr');
                    _weFeedId = _tr.attr('wefeedid');
                    fetchModal.modal('show');
                });
                //绑定确定提交事件
                confirmAction.unbind('click');
                confirmAction.bind('click', function(){
                    confirmFetch(function(){
                        fetchModal.modal('hide')
                    });
                });
                function confirmFetch(cb){
                    var loadingArea = $('.modal-content', fetchModal);
                    Kit.loading.show(loadingArea);
                    var params = {
                        id :_weFeedId
                    };
                    http.work('/feed/fetchNow',params,'POST').then(function(res){
                        _tr.addClass("p-ongoing");
                        //实时更新feed发布状态
                        _this.updataState();
                        cb();
                        Kit.loading.hide(loadingArea);
                    });
                }
            }
            /*
             @时间静态数据
             * */
            ,getHour: function(){
                var operatingSystem = [{
                    value: '0',
                    text: '00:00'
                },{
                    value: 1,
                    text: '01:00'
                },{
                    value: 2,
                    text: '02:00'
                },{
                    value: 3,
                    text: '03:00'
                },{
                    value: 4,
                    text: '04:00'
                },{
                    value: 5,
                    text: '05:00'
                },{
                    value: 6,
                    text: '06:00'
                },{
                    value: 7,
                    text: '07:00'
                },{
                    value: 8,
                    text: '08:00'
                },{
                    value: 9,
                    text: '09:00'
                },{
                    value: 10,
                    text: '10:00'
                },{
                    value: 11,
                    text: '11:00'
                },{
                    value: 12,
                    text: '12:00'
                },{
                    value: 13,
                    text: '13:00'
                },{
                    value: 14,
                    text: '14:00'
                },{
                    value: 15,
                    text: '15:00'
                },{
                    value: 16,
                    text: '16:00'
                },{
                    value: 17,
                    text: '17:00'
                },{
                    value: 18,
                    text: '18:00'
                },{
                    value: 19,
                    text: '19:00'
                },{
                    value: 20,
                    text: '20:00'
                },{
                    value: 21,
                    text: '21:00'
                },{
                    value: 22,
                    text: '22:00'
                },{
                    value: 23,
                    text: '23:00'
                }];
                return operatingSystem;
            }
        }
        return feedList;
    });
